<?php

/**
 *  http服务,此处是用作api接口服务器
 */
$http = new Swoole\Http\Server("0.0.0.0", 9502);
$http->set([
    'worker_num' => 2,
    'daemonize' => false,
    'task_worker_num' => 2,
    'max_conn' => 1000,
    'enable_coroutine' => false,
]);

$http->on('WorkerStart', function($http, $worker_id) {
    define('APP_PATH', __DIR__ . '/../application/');
    require_once __DIR__ . '/../thinkphp/start.php';
    // 注册命名空间
    $server_path = str_replace('\\', '/', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'server');
    \think\Loader::addNamespace('server', $server_path);
});

$http->on('request', function ($request, $response)use($http) {
    // 过滤多余的请求
    if($request->server['request_uri'] == '/favicon.ico') {
        $response->status(404);
        $response->end();
        return;
    }
    //将 post、get等全局变量清空
    $_GET = [];
    if (isset($request->get) && !empty($request->get)) {
        foreach ($request->get as $k => $v) {
            $_GET[$k] = $v;
        }
    }
    $_POST = [];
    if (isset($request->post) && !empty($request->post)) {
        foreach ($request->post as $k => $v) {
            $_POST[$k] = $v;
        }
    }

    // 处理post的json提交的数据
    $post_string = $request->rawContent();
    if (!empty($post_string) && $request->header['content-type'] == 'application/json') {
        $post_arr = json_decode($post_string, true);
        foreach ($post_arr as $key => $val) {
            $_POST[$key] = $val;
        }
    }

    $_POST['http_server'] = $http; // 注入http服务对象
    // 执行应用并响应
    ob_start();
    try {
        \think\Container::get('app')->run()->send();
    } catch ( \Exception $e) {
        echo $e->getMessage();
    }
    $content = ob_get_contents();
    ob_end_clean();
    $response->end($content);
    //$http->close();
});

$http->on('task', 'onTask'); // 同步事件，接收worker投递的任务，task_num的设置需要参照任务执行的时间及worker投递任务的时间
$http->on('finish', 'onFinish'); // task完成时触发
$http->on('close', 'onClose'); //

/**
 * @param \Swoole\Http\Server $serv
 * @param $task_id
 * @param $work_id
 * @param $task_root
 * @throws Exception
 */
function onTask(Swoole\Http\Server $serv, $task_id, $work_id, $task_root) {
    try {
        $taskM = new $task_root();
        if ($taskM  instanceof \server\core\AbstractTask) {
            $response = $taskM->execute();
            $res = ['response' => $response, 'finish' => $taskM];
            $serv->finish($res);
        } else {
            throw new Exception('投递的task任务第一个参数必须是继承AbstractTask的类');
        }
    } catch (\Exception $e) {
        throw new Exception('投递task任务失败：' . $e->getMessage());
    }
}


function onFinish(Swoole\Http\Server $http, $task_id, $data)
{
    $finish_data = $data['response'];
    $finishM = $data['finish'];
    $finishM->finish($finish_data);
}

function onClose(Swoole\Http\Server $server, $fd, $from_id) {
    echo 'close:' . 'OK' . PHP_EOL;
}

// 启动服务器
$http->start();